package org.example.controller;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.example.pojo.Result;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.JWTUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;


@Slf4j
@RestController
public class LoginRegisterController {
    @Autowired
    private UserService userService;

//    @PostMapping(value = "/login")
//    public Result login(User loginUser) {
    @PostMapping(value = "/login", consumes = "application/json")
    public Result login(@RequestBody User loginUser) {
        String name = loginUser.getName();
        String password = loginUser.getPassword();
        User user = userService.login(name, password);
        if(user == null) {
            log.info("用户{}登录失败", name);
            return Result.error("用户名或密码错误");
        } else {
            String jwtToken = JWTUtils.generateToken(user.toMap());
            log.info("用户{}登录成功，生成的token = {}", user.getName(), jwtToken);
            Object data = new Object() {
                public Integer id = user.getId();
                public String jwt = jwtToken;
            };
            return Result.success(data);
        }
    }

    @PostMapping(value = "/register", consumes = "multipart/form-data")
    public Result register(@RequestPart(value = "image", required = false) MultipartFile imageFile,
                           @RequestPart("name") String name,
                           @RequestPart("password") String password) {
        if(userService.register(name, password, imageFile)) {
            log.info("用户{}注册成功", name);
            return Result.success();
        } else {
            log.info("用户{}注册失败", name);
            return Result.error("用户名已存在");
        }
    }
}
